



//
//  LeeFaBiaoHuodongVCViewController.m
//  firstpoint
//
//  Created by 李雪虎 on 2017/7/24.
//  Copyright © 2017年 xzcysoft. All rights reserved.
//

#import "LeeFaBiaoHuodongVCViewController.h"
#import "TZImagePickerController.h"
#import "CollectionViewCell.h"

#define Kwidth [UIScreen mainScreen].bounds.size.width
#define Kheight [UIScreen mainScreen].bounds.size.height
@interface LeeFaBiaoHuodongVCViewController ()<UITextViewDelegate,UICollectionViewDelegate, UICollectionViewDataSource,TZImagePickerControllerDelegate>
{
    CGFloat _itemWH;
    CGFloat _margin;
    UIImage *upImg;
}
@property(nonatomic,strong)UILabel *tishiLable;
@property(nonatomic,strong)UIView *BigView;
@property(nonatomic,strong)UIButton *addButton;
@property (nonatomic, assign) CGSize assetSize;
@property (nonatomic,strong)UITextView *textView;
@property (nonatomic, copy)NSArray <UIImage *> * assets;
@property (nonatomic,strong)NSArray <NSData *> * dataArray;
@property (nonatomic ,strong) UICollectionView *collectionView;
@property (nonatomic ,strong) NSMutableArray *photosArray;
@property (nonatomic ,strong) NSMutableArray *assestArray;
@property BOOL isSelectOriginalPhoto;
@end

@implementation LeeFaBiaoHuodongVCViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"发表动态";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.hidden = NO;
    [self addTextView];//textVeiw
    
    UIButton *fabiaoBtn= [UIButton buttonWithType:UIButtonTypeCustom];
    fabiaoBtn.frame = CGRectMake(0, height_screen-60, width_screen, 60);
    fabiaoBtn.backgroundColor =[UIColor orangeColor];
    [fabiaoBtn addTarget:self action:@selector(tijiaoHttpURL) forControlEvents:UIControlEventTouchUpInside];
    [fabiaoBtn setTitle:@"确认提交" forState:UIControlStateNormal];
    [self.view addSubview:fabiaoBtn];
    
    [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:self.collectionView];
    
    
    // Do any additional setup after loading the view.
}
- (NSMutableArray *)photosArray{
    if (!_photosArray) {
        self.photosArray = [NSMutableArray array];
    }
    return _photosArray;
}

- (NSMutableArray *)assestArray{
    if (!_assestArray) {
        self.assestArray = [NSMutableArray array];
    }
    return _assestArray;
}

-(UICollectionView *)collectionView{
    if (!_collectionView) {
        _margin = 4;
        _itemWH = (self.view.bounds.size.width - 2 * _margin - 4) / 3 - _margin;
        UICollectionViewFlowLayout *flowLayOut = [[UICollectionViewFlowLayout alloc] init];
        flowLayOut.itemSize = CGSizeMake((Kwidth - 50)/ 4, (Kwidth - 50)/ 4);
        flowLayOut.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 240, Kwidth, 300) collectionViewLayout:flowLayOut];
        
        
        _collectionView.backgroundColor = [UIColor whiteColor];
        
        
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        //        self.collectionView.scrollEnabled = NO;
    }
    return _collectionView;
}
-(void)addTextView{
    _textView = [[UITextView alloc]initWithFrame:CGRectMake(10, 20+64, width_screen-20, 150)];
    self.automaticallyAdjustsScrollViewInsets=NO;
    _textView.editable = YES;
    _textView.textAlignment = NSTextAlignmentLeft;
    _textView.backgroundColor = LRRGBColor(242, 246, 247);
    _textView.delegate = self;
    [_textView.layer setMasksToBounds:YES];
    //边框宽度
    [_textView.layer setBorderWidth:1.0];
    //边框圆角半径
    [_textView.layer setCornerRadius:5.0];
    //边框颜色
    _textView.layer.borderColor=[UIColor grayColor].CGColor;
    _textView.font = [UIFont systemFontOfSize:18];
    [self.view addSubview:_textView];
    //提示文字
    _tishiLable = [[UILabel alloc]initWithFrame:CGRectMake(5, 10, 200, 20)];
    _tishiLable.text = @"添加备注说明...";
    _tishiLable.textColor = LRRGBColor(131, 132, 135);
    [_textView addSubview:_tishiLable];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 265, width_screen-100, 20)];
    label.textColor = LRRGBColor(0, 0, 0);
    label.text = @"活动图片或截图";
    label.font = [UIFont systemFontOfSize:18];
    [self.view addSubview:label];
}
#pragma mark---textViewDeleget
//正在改变
- (void)textViewDidChange:(UITextView *)textView{
    
    self.tishiLable.hidden = YES;
    //字数限制操作
    if (textView.text.length >= 100) {
        
        textView.text = [textView.text substringToIndex:100];
        
    }
    //取消按钮点击权限，并显示提示文字
    if (textView.text.length == 0) {
        
        self.tishiLable.hidden = NO;
        
        
    }
}
-(void)addtupainButton{
    for (int i=0; i<self.assets.count; i++) {
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(20+((width_screen-80)/3+20)*(i%3), 20+((width_screen-80)/3+20)*(i/3), (width_screen-80)/3, (width_screen-80)/3)];
        
        imgView.image = self.assets[i];
        
        [_BigView addSubview:imgView];
        
        
        
    }
    
    
    if (self.assets.count==7) {
        _BigView.frame = CGRectMake(0, 280, width_screen,(width_screen-80)/3+((width_screen-80)/3+40) *(self.assets.count/3));
    }else{
        _BigView.frame = CGRectMake(0, 280, width_screen,(width_screen-80)/3+((width_screen-80)/3+40) *(self.assets.count/4));
    }
    if (self.assets.count<4) {
        _addButton.frame = CGRectMake(20, (_BigView.frame.origin.y+_BigView.frame.size.height+40), (width_screen-80)/3, (width_screen-80)/3);
    }else{
        _addButton.frame = CGRectMake(20, (_BigView.frame.origin.y+_BigView.frame.size.height+20), (width_screen-80)/3, (width_screen-80)/3);
    }
    
    
    
}
#pragma mark ---提交按钮事件
-(void)tijiaoHttpURL{
    NSInteger taskId = [_idString integerValue];
    NSString *url = [NSString stringWithFormat:@"%@%@",LINK_BASE_URL(@"task/allodsGold.api?access_token="),NSUD_Obj(@"token")];
    __weak typeof(self) waekself =self;
    [HTTPURL postRequest:url parameters:@{@"taskId":@(taskId),@"userId":userid,@"finishAudit":@(_finishAudit),@"notes":_textView.text} success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@",responseObject);
        if ([responseObject[@"retInfo"]intValue]==1) {
            [waekself promptViewmessage:responseObject[@"retInfo"] sureBlock:^{
                [waekself.navigationController popToRootViewControllerAnimated:YES];
            }];
        }
    } filure:^(NSURLSessionDataTask *task, id error) {
        NSLog(@"%@",error);
    }];
    NSLog(@"%lu",(unsigned long)self.assets.count);
    if (self.assets.count>0) {
        
        for (int a=0; a<self.assets.count; a++) {
            
            [self youtupian:self.assets[a]];
            
        }
   
    }
    
    
    
    
}
-(void)youtupian:(UIImage *)img
{
        NSString*tokenStr= OBJECT_FOR_KEY(@"token");
        NSString*urlStr=[NSString stringWithFormat:@"common/file/upload.api?access_token=%@",tokenStr];
        
        NSData*data;
        upImg=  [self scaleToSize:img size:CGSizeMake(150, 150)];
        if (UIImagePNGRepresentation(upImg)) {
            data=  UIImagePNGRepresentation(upImg);
            
        }else
        {
            data=  UIImageJPEGRepresentation(upImg,1);
            
        }
        NSLog(@"%@",data);
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                             
                                                             @"text/html",
                                                             
                                                             @"image/jpeg",
                                                             
                                                             @"image/png",
                                                             
                                                             @"application/octet-stream",
                                                             
                                                             @"text/json",
                                                             
                                                             nil];
        
        manager.requestSerializer= [AFHTTPRequestSerializer serializer];
        
        manager.responseSerializer= [AFHTTPResponseSerializer serializer];
        
        [manager POST:LINK_BASE_URL(urlStr)  parameters:@{@"userId":userid,@"category":@"23"} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            //        UIImage *image = [UIImage imageNamed:@"gauge.png"];
            //
            //        NSData *data = UIImagePNGRepresentation(image);
            
            //上传的参数(上传图片，以文件流的格式)
            
            [formData appendPartWithFileData:data
             
                                        name:@"uploadFile"
             
                                    fileName:@"gauge.jpg"
             
                                    mimeType:@"image/jpg"];
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
            
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSLog(@"上传成功");
            NSLog(@"%@",responseObject);
            
            
            
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"上传失败%@",error);
            
            
            
        }];
        
}

-(UIImage *)scaleToSize:(UIImage *)image size:(CGSize)size
{
    //创建一个bitmap的context
    //并把他设置成当前的context
    UIGraphicsBeginImageContext(size);
    //绘制图片的大小
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    //从当前context中创建一个改变大小后的图片
    UIImage *endImage=UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return endImage;
}
//提示框
-(void)promptViewmessage:(NSString *)message sureBlock:(void(^)())sureBlock
{
    UIAlertController * alert= [UICommonView showOneAlertWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert sureTitle:@"确实" sureBlock:^{
        sureBlock();
    }];
    [self presentViewController:alert animated:YES completion:nil];
}



- (void)checkLocalPhoto{
    
    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    [imagePicker setSortAscendingByModificationDate:NO];
    imagePicker.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    imagePicker.selectedAssets = _assestArray;
    imagePicker.allowPickingVideo = NO;
    [self presentViewController:imagePicker animated:YES completion:nil];
    
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    self.photosArray = [NSMutableArray arrayWithArray:photos];
    self.assestArray = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [_collectionView reloadData];
    
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == _photosArray.count) {
        [self checkLocalPhoto];
    }else{
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_assestArray selectedPhotos:_photosArray index:indexPath.row];
        imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            _photosArray = [NSMutableArray arrayWithArray:photos];
            _assestArray = [NSMutableArray arrayWithArray:assets];
            _isSelectOriginalPhoto = isSelectOriginalPhoto;
            [_collectionView reloadData];
            _collectionView.contentSize = CGSizeMake(0, ((_photosArray.count + 2) / 3 ) * (_margin + _itemWH));
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _photosArray.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    if (indexPath.row == _photosArray.count) {
        cell.imagev.image = [UIImage imageNamed:@"AlbumAddBtn@2x"];
        //        cell.imagev.backgroundColor = [UIColor redColor];
        cell.deleteButton.hidden = YES;
        
    }else{
        cell.imagev.image = _photosArray[indexPath.row];
        cell.deleteButton.hidden = NO;
    }
    cell.deleteButton.tag = 100 + indexPath.row;
    [cell.deleteButton addTarget:self action:@selector(deletePhotos:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
    
}

- (void)deletePhotos:(UIButton *)sender{
    [_photosArray removeObjectAtIndex:sender.tag - 100];
    [_assestArray removeObjectAtIndex:sender.tag - 100];
    [_collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag-100 inSection:0];
        [_collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [_collectionView reloadData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
